package open.intellijboy.framework.core.exception;

import jakarta.annotation.Nullable;
import lombok.Getter;
import open.intellijboy.framework.core.response.StatusCode;

import java.util.Optional;

/**
 * 基础异常类 - 所有自定义异常的基类
 *
 * @author System
 * @version 1.0.0
 * @since 2024-01-01
 */
@Getter
public abstract class BaseException extends RuntimeException {

    /**
     * 错误枚举对象
     */
    @Nullable
    private StatusCode errorStatusCode;

    /**
     * 错误码
     */
    private final String errorCode;

    /**
     * 错误消息
     */
    private final String errorMessage;

    /**
     * 构造函数
     *
     * @param errorStatusCode 错误码枚举对象
     */
    protected BaseException(StatusCode errorStatusCode) {
        this.errorStatusCode = errorStatusCode;
        this.errorCode = errorStatusCode.getCode();
        this.errorMessage = errorStatusCode.getDescription();
    }

    /**
     * 构造函数
     *
     * @param errorCode    错误码
     * @param errorMessage 错误消息
     */
    protected BaseException(String errorCode, String errorMessage) {
        super(errorMessage);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    /**
     * 构造函数
     *
     * @param errorCode    错误码
     * @param errorMessage 错误消息
     * @param cause        原因异常
     */
    protected BaseException(String errorCode, String errorMessage, Throwable cause) {
        super(errorMessage, cause);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    @Nullable
    public StatusCode getErrorStatusCode() {
        return errorStatusCode;
    }

    /**
     * 获取错误消息内容
     *
     * @return 返回错误消息提示内容
     */
    public String getErrorMessage() {
        return Optional.ofNullable(this.getErrorStatusCode())
                       .map(StatusCode::getPrettyExceptionMessage)
                       .orElse(this.errorMessage);
    }
}

